package com.aaa.utils;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2022/7/27 9:09
 * @description：dao的基类
 * @modified By：
 * @version: 1.0
 */
public class BaseDao {
    /**
     * 四大金刚
     */
    static String driver = "com.mysql.jdbc.Driver";
    static String url = "jdbc:mysql://localhost:3306/qy156?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
    static String username = "root";
    static String password = "root";

    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 1、加载驱动
     */
    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 2、获取数据库连接
     */
    public Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * @param sql    sql语句
     * @param params 传入的参数，不固定
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 增删改的通用方
     */
    public boolean executeUpdate(String sql, Object... params) {
        Connection connection = this.getConnection();
        //获取PreparedStatement 对象
        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement(sql);
            //设置占位符
            if (null != params && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    /**
                     *      * @param parameterIndex the first parameter is 1, the second is 2, ...
                     *      * @param x the object containing the input parameter value
                     */
                    ps.setObject(i + 1, params[i]);
                }
            }
            //执行sql
            int update = ps.executeUpdate();
            if (update > 0) {
                System.out.println("操作成功！");
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (ps != null) {
                try {
                    //关闭ps对象
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    //关闭数据库连接
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("操作失败！");
        return false;
    }

    public PreparedStatement setParam(PreparedStatement ps, Object... params) {
        if (null != params && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                /**
                 *      * @param parameterIndex the first parameter is 1, the second is 2, ...
                 *      * @param x the object containing the input parameter value
                 */
                try {
                    ps.setObject(i + 1, params[i]);

                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }
        return ps;
    }


    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 通用的关闭数据库连接方法
     * @create time: 2022/7/27 11:31
     * @param resultSet
     * @param ps
     * @param connection
     * @return
     */
    public void closeConnection(ResultSet resultSet,PreparedStatement ps,Connection connection){
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                //关闭ps对象
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                //关闭数据库连接
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * @param sql    sql语句
     * @param params 传入的参数，不固定
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 通用的查询方法
     */
    public List<Map<String, Object>> executeQuery(String sql, Object... params) {
        Connection connection = this.getConnection();
        //获取PreparedStatement 对象
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            ps = connection.prepareStatement(sql);
            //设置占位符
            ps=this.setParam(ps,params);
            //执行sql
            resultSet = ps.executeQuery();
            //获取总列数
            //metaData 元数据，主要保存的是表接口，不包含行数据，
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
           /* System.out.println("columnCount总列数：" + columnCount);*/
            //定义一个list集合，封装多行数据
            List<Map<String, Object>> rowList = new ArrayList<>();
            while (resultSet.next()) {
                //jdbc默认下标从1开始
                Map map = new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    //获取列名
                    String columnName = metaData.getColumnName(i);
                    //获取列值
                    Object columnValue = resultSet.getObject(columnName);
                    map.put(columnName, columnValue);

                }
                rowList.add(map);
            }
            return rowList;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeConnection(resultSet,ps,connection);
        }
        System.out.println("操作失败！");
        return null;
    }

    /**
     * @param sql    sql语句
     * @param params 传入的参数，不固定
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 增删改的通用方
     */
    public Integer executeUpdateKey(String sql, Object... params) {
        Connection connection = this.getConnection();
        //获取PreparedStatement 对象
        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            //设置占位符
            ps=this.setParam(ps,params);
            //执行sql
            int update = ps.executeUpdate();
            if (update > 0) {
                System.out.println("操作成功！");
                //返回带主键的结果集
                ResultSet generatedKeys = ps.getGeneratedKeys();
                //解析结果集
                if (generatedKeys.next()) {
                    //获取主键值
                    int keysInt = generatedKeys.getInt(1);
                    return keysInt;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeConnection(null,ps,connection);
        }
        System.out.println("操作失败！");
        return 0;
    }

}
